import React, { createRef, PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import { message, Select, Table } from 'antd'
import _ from 'lodash'
import { BreadcrumbBar, Logger, ProTable, ProTableOperate, ProTableOptions } from '@/components'
import { getHashParameterByName } from '@/utils/helper'
import Tools from '@/utils/Tools'
import styles from './index.less'

const Bus = Tools.Bus

const { OperateItem } = ProTableOperate
const { Option } = Select

@connect(({ operation }) => ({ ...operation }))
class OperationHistory extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      query: {
        nodeId: getHashParameterByName('nodeId'),
        execType: getHashParameterByName('execType') || '',
      },
      executeType: getHashParameterByName('execType') || '',
      taskStatus: '',
      menus: [{ name: '任务运维' }, { name: '历史任务' }],
      columns: [
        {
          title: '任务名称',
          width: '15%',
          dataIndex: 'nodeName',
          key: 'datadevTaskName',
          ellipsis: true,
          render: (nodeName, record) => (
            <span>{nodeName === "开始节点" ? <span>{nodeName}</span> : <span className={styles.link} onClick={() => { this.queryGetParentType(record?.nodeId, nodeName) }}>{nodeName}</span>}</span>
          ),
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          key: 'status',
          width: '8%',
          ellipsis: true,
          render: (statusParams) => (
            <>
              {
                statusParams === 1 && (
                  <><i className="iconfont icon-weiyunhang hu-blue" /> 未运行</>
                )
              }
              {
                statusParams === 2 && (
                  <><i className="iconfont icon-yunhangzhong_1 hu-blue" /> 运行中</>
                )
              }
              {
                statusParams === 3 && (
                  <><i className="iconfont icon-chenggong hu-green" /> 成功</>
                )
              }
              {
                statusParams === 4 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 失败</>
                )
              }
              {
                statusParams === 5 && (
                  <><i className="iconfont icon-weiyunhang hu-gray" /> 停止</>
                )
              }
              {
                statusParams === 6 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 部分失败</>
                )
              }
              {
                statusParams === 9 && (
                  <><i className="iconfont icon-guidang hu-blue" /> 已归档</>
                )
              }
            </>
          ),
        },
        {
          title: '任务类型',
          dataIndex: 'execType',
          key: 'execType',
          width: '8%',
          ellipsis: true,
          render: (execType) => (
            <>
              {execType === 0 && '手动执行'}
              {execType === 1 && '周期执行'}
            </>
          ),
        },

        {
          title: '启动时间',
          width: '15%',
          dataIndex: 'startTime',
          key: 'startTime',
          ellipsis: true,
          onFilter: (value, record) => record.address.indexOf(value) === 0,
          sorter: (a, b) => false,
          sortDirections: ['descend', 'ascend'],
        },
        {
          title: '结束时间',
          width: '15%',
          dataIndex: 'endTime',
          key: 'endTime',
          ellipsis: true,
          onFilter: (value, record) => record.address.indexOf(value) === 0,
          sorter: (a, b) => false,
          sortDirections: ['descend', 'ascend'],
        },
        {
          title: '运行时长（秒）',
          width: '15%',
          dataIndex: 'time',
          key: 'time',
          // ellipsis: true,
          render: (text) => <span>{text}</span>,
          onFilter: (value, record) => record.address.indexOf(value) === 0,
          sorter: (a, b) => false,
          sortDirections: ['descend', 'ascend'],
        },
        {
          title: '责任人', width: '10%', dataIndex: 'userName', key: 'userName', ellipsis: true,
        },
        {
          title: '操作',
          // dataIndex: 'action',
          // key: 'action',

          width: '15%',
          ellipsis: true,
          render: (record) => {
            const {
              id, nodeId, status, haveChildren,
            } = record
            return (
              <ProTableOptions>
                {/* <span onClick={() => { */}
                {/*  this.setState({ */}
                {/*    id: record.jobLogId, */}
                {/*  }) */}
                {/* }} */}
                {/* >查看日志 */}
                {/* </span> */}

                {
                  (record.haveChildren || null)
                  && (
                    <span
                      onClick={() => { history.push(`/data-development/offline/operation-detail?nodeId=${record.nodeId}`) }}
                    >
                      任务详情
                    </span>
                  )
                }
                <span
                  onClick={() => {
                    // this.Logger.iconUpFn()
                    this.setState({
                      loggerList: [],
                    })
                    // this.fetchLogger(record.id, this.state.offsets, false)
                    this.viewLog(record.id, this.state.offsets, false)
                    Bus.emit('iconUpFn2')
                  }}
                >
                  查看日志
                </span>
                {
                  (status === 2 || null) && (
                    <span onClick={() => {
                      this.setState({
                        loggerList: [],
                        expandedRowKeys: [],
                      })
                      this.stopRun(id, true)
                    }}
                    >
                      终止运行
                    </span>
                  )
                }
              </ProTableOptions>
            )
          },
        },
      ],
      isHideLogger: true,
      expandedRowKeys: [],
      subTablesData: {},
      expandedTableLoading: {},
      forceUpdateKey: 0,
    }
    this.tableRef = createRef()
  }

  componentDidMount() {
    this.querySummary()
  }

  queryGetParentType = (nodeId, nodeName) => {
    this.props.dispatch({
      type: 'operation/queryGetParentType',
      params: {
        nodeId,
      },
      cb: (res) => {
        const { msg, status, data } = res
        if (status === 200) {
          this.props.dispatch({
            type: 'operation/saveFilterValue',
            params: {
              activeTabKey: ''
            },
          })

          if (data === 1) {
            // 作业开发
            history.push(`/data-development/offline/script-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          } else {
            history.push(`/data-development/offline/workflow-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          }
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 查看日志
  viewLog = (jobId, offsets, bool) => {
    clearInterval(this.time)
    this.setState({
      loading: true,
      isHideLogger: false,
    })
    this.props.dispatch({
      type: 'operation/queryLog',
      params: {
        jobId,
        offset: offsets || 0, // 参考老版本，传了固定值
      },
      cb: (res) => {
        const { status, msg, data } = res || {}
        this.setState({
          loading: false,
        })
        const domWrapper = document.querySelector('#layout_container_content')
        const currentScroll = domWrapper.scrollTop // 已经被卷掉的高度
        const scrollHeight = domWrapper.scrollHeight // 内容总高度
        domWrapper.scrollTo(0, (scrollHeight - currentScroll))

        if (status === 200) {
          this.setState((prevState) => ({
            loggerList: prevState.loggerList.concat(data?.logContent),
          }))
          this.time = setInterval(() => {
            if (data?.logEnd && bool) {
              // this.fetchData()
              // this.setState((prevSta) => ({
              //   forceUpdateKey: prevSta.forceUpdateKey + 1,
              // }))
              clearInterval(this.time)
            } else if (data?.logEnd) {
              clearInterval(this.time)
            } else {
              this.viewLog(jobId, data?.offset, bool)
            }
          }, 4000)
        } else {
          message.warn(msg || '系统异常，请稍后重试~')
        }
      },
    })
  }

  querySummary = () => {
    this.props.dispatch({
      type: 'operation/querySummary',
      params: {
        nodeId: getHashParameterByName('nodeId'),
      },
      cb: (res) => {
        const {
          successNum, failedNum,
        } = res || {}
        this.setState({
          successNum,
          failedNum,
        })
      },
    })
  }

  expandedRowRender = (record) => {
    const { id } = record
    const { subTablesData, expandedTableLoading } = this.state
    const copyColumns = _.cloneDeep(this.state.columns) || []
    copyColumns.splice(0, 1)
    copyColumns.splice(copyColumns.length - 1, 1)
    const columns = [
      {
        title: '任务名称',
        dataIndex: 'nodeName',
        key: 'nodeName',
        width: '15%',
        ellipsis: true,
        render: (nodeName, record) => (
          <span>{nodeName === "开始节点" ? <span>{nodeName}</span> : <span className={styles.link} onClick={() => { this.queryGetParentType(record?.nodeId, nodeName) }}>{nodeName}</span>}</span>
        ),
      },
      ...copyColumns,
      {
        title: '操作',
        width: '15%',
        render: (subRecord) => {
          const { id: idParams } = subRecord || {}
          return (
            <ProTableOptions>
              <span onClick={
                () => {
                  this.setState({
                    loggerList: [],
                  })
                  this.viewLog(idParams, this.state.offsets, false)
                  Bus.emit('iconUpFn2')
                }
              }
              >查看日志
              </span>
            </ProTableOptions>
          )
        },
      },
    ]

    return (
      <Table
        loading={!!expandedTableLoading[id]}
        rowKey="id"
        columns={columns}
        dataSource={subTablesData[id] || []}
        pagination={false}
      />
    )
  }

  // 点击展开按钮发请求操作
  handleExpand = (expanded, record) => {
    const { id } = record
    if (expanded) {
      this.setState((prevState) => ({
        expandedRowKeys: [...prevState.expandedRowKeys, id],
        expandedTableLoading: {
          ...prevState.expandedTableLoading,
          [id]: true,
        },
      }))

      this.props.dispatch({
        type: 'operation/queryJobChildren',
        params: { jobId: id },
        cb: (res) => {
          this.setState((prevState) => ({
            subTablesData: {
              ...prevState.subTablesData,
              [id]: res,
            },
            expandedTableLoading: {
              ...prevState.expandedTableLoading,
              [id]: false,
            },
          }))
        },
      })
    } else {
      const { expandedRowKeys } = this.state
      const filterArr = expandedRowKeys.filter(item => item !== id)
      this.setState({
        expandedRowKeys: [...filterArr],
      })
    }
  }

  // 终止运行
  stopRun = (jobId, bool) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'operation/queryStop',
      params: {
        logIds: jobId,
      },
      cb: (res) => {
        // 后端需要2s的延时执行
        setTimeout(() => {
          this.setState({ loading: false })
          this.querySummary()

          const { status, msg } = res
          if (status === 200) {
            message.success('操作成功')
            this.viewLog(jobId, 0, bool)
            this.setState((prevSta) => ({
              forceUpdateKey: prevSta.forceUpdateKey + 1,
            }))
          } else {
            message.error(msg || '系统异常，请稍后重试~')
          }
        }, 2000)
      },
    })
  };

  render() {
    const {
      query, executeType, taskStatus, menus, loggerList, successNum, failedNum, expandedRowKeys, columns, loading, isHideLogger, forceUpdateKey,
    } = this.state
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i onClick={() => { history.push('/data-development/offline/task-operation') }} className="iconfont icon-zuo" />
          <span onClick={() => { history.push('/data-development/offline/task-operation') }}>历史任务</span>
        </div>
        <div className={styles.page_content_column}>
          <div className={`${styles.page_content_right} ${styles.page_content_right_flex}`}>
            <div className={styles.data_show}>
              <div className={styles.item}>
                <div><span className={styles.column}>成功数</span> <span className={styles.count}>{successNum || 0}</span></div>
                <i className="iconfont-colour2 icon-chenggong_1" />
              </div>
              <div className={styles.item}>
                <div><span className={styles.column}>失败数</span> <span className={styles.count}>{failedNum || 0}</span></div>
                <i className="iconfont-colour2 icon-shibai_1" />
              </div>
            </div>
            <ProTableOperate style={{ marginBottom: 12 }}>
              <OperateItem>
                <span>任务状态</span>
                <Select
                  allowClear
                  placeholder="请选择任务状态"
                  onChange={(value) => {
                    this.setState({
                      taskStatus: value,
                    }, () => {
                      this.tableRef?.current?.resetPageNum()
                      this.setState({
                        query: {
                          ...query,
                          execType: executeType || '',
                          taskStatus: value || '',
                        },
                      })
                    })
                  }}
                >
                  <Option value={1}>未运行</Option>
                  <Option value={2}>运行中</Option>
                  <Option value={3}>成功</Option>
                  <Option value={4}>失败</Option>
                  <Option value={5}>停止</Option>
                  <Option value={6}>部分失败</Option>
                  <Option value={9}>已归档</Option>
                </Select>
              </OperateItem>
              <OperateItem>
                <span>任务类型</span>
                <Select
                  defaultValue={getHashParameterByName('execType')}
                  allowClear
                  placeholder="请选择任务类型"
                  onChange={(value) => {
                    this.setState({
                      executeType: value,
                    }, () => {
                      this.tableRef?.current?.resetPageNum()
                      this.setState({
                        query: {
                          ...query,
                          execType: value || '',
                          taskStatus: taskStatus || '',
                        },
                      })
                    })
                  }}
                >
                  <Option value="1">周期执行</Option>
                  <Option value="0">手动执行</Option>
                </Select>
              </OperateItem>
            </ProTableOperate>
            <ProTable
              key={forceUpdateKey}
              loading={loading}
              ref={this.tableRef}
              rowKey="id"
              columns={columns}
              query={query}
              border={false}
              url="/api/v1/offlineDev/operation/jobHistory"
              expandedRowKeys={expandedRowKeys}
              expandable={{
                expandedRowRender: this.expandedRowRender,
                onExpand: this.handleExpand,
                rowExpandable: record => record.haveChildren,
                indentSize: 0,
              }}
              resetExpandedRowKeys={this.resetExpandedRowKeys}
            />
          </div>
          {/* <Logger */}
          {/*  list={loggerList || []} */}
          {/*  url={id ? `/api/v1/xxl/joblog/logDetailPage?id=${id}` : null} */}
          {/* /> */}
          <Logger
            className={`${isHideLogger ? styles.hideLogger : ''}`}
            list={loggerList || []}
          />
        </div>
      </div>
    )
  }
}

export default OperationHistory
